<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房间状态" prop="roomStatus">
        <el-select v-model="queryParams.roomStatus" placeholder="请选择房间状态" clearable>
          <el-option
              v-for="dict in apartment_room_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="月租" prop="roomMonthRent">
        <el-select v-model="queryParams.roomMonthRent" placeholder="请选择月租" clearable>
          <el-option
              v-for="rent in uniqueMonthRents"
              :key="rent"
              :label="rent"
              :value="rent"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公寓名称" prop="flatsId">
        <el-select v-model="queryParams.flatsId" placeholder="请输入公寓名称" clearable>
          <el-option
              v-for="flats in flatsList"
              :key="flats.flatsId"
              :label="flats.flatsName"
              :value="flats.flatsId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房间面积" prop="roomSize">
        <el-select v-model="queryParams.roomSize" placeholder="请输入公寓名称" clearable>
          <el-option
              v-for="rent in uniqueRoomSizes"
              :key="rent"
              :label="rent"
              :value="rent"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['apartment:room:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['apartment:room:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['apartment:room:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['apartment:room:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" prop="roomId" />
      <el-table-column label="房间名称" align="center" prop="roomName" />
      <el-table-column label="所属公寓" align="center" prop="flatsName" />
      <el-table-column label="房间月租" align="center" prop="roomMonthRent" />
      <el-table-column label="房间面积" align="center" prop="roomSize" />
      <el-table-column label="房间图片" align="center" prop="imagePath" >
        <template #default="scope">
          <image-preview
              :src="scope.row.roomImagePath ? scope.row.roomImagePath.split(',')[0] : ''"
              style="width: 50px; height: 50px;"
              :preview-src-list="scope.row.roomImagePath ? scope.row.roomImagePath.split(',') : []"
          ></image-preview>
        </template>
      </el-table-column>
      <el-table-column label="房间状态" align="center" prop="roomStatus">
        <template #default="scope">
          <dict-tag :options="apartment_room_status" :value="scope.row.roomStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="房间可用性" align="center" prop="roomUseNo" width="100">
        <template #default="scope">
          <el-switch
              v-model="scope.row.roomUseNo"
              active-value="0"
              inactive-value="1"
              active-text="可用"
              inactive-text="停用"
              @change="handleUseNoChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" @click="handleViewDetails(scope.row)" v-hasPermi="['apartment:room:query']">查看详情</el-button>
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['apartment:room:edit']">修改</el-button>
          <el-button link type="primary"  @click="handleDelete(scope.row)" v-hasPermi="['apartment:room:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改房间管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roomRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房间名称" prop="roomName" >
          <el-input v-model="form.roomName" type="text" placeholder="请输入房间名称" clearable />
        </el-form-item>

        <el-form-item label="公寓名称" prop="flatsId">
          <el-select v-model="form.flatsId" placeholder="请输入公寓名称" clearable>
            <el-option
                v-for="flats in flatsList"
                :key="flats.flatsId"
                :label="flats.flatsName"
                :value="flats.flatsId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间月租" prop="roomMonthRent">
          <NumberCounter :initialValue="2000" :min="100" :max="10000" :step="50"   v-model="form.roomMonthRent" />
        </el-form-item>
        <el-form-item label="房间面积" prop="roomSize">
          <el-input v-model="form.roomSize" type="text" placeholder="请输入房间面积" clearable />
        </el-form-item>
        <el-form-item label="房间状态" prop="roomStatus">
          <el-radio-group v-model="form.roomStatus">
            <el-radio
                v-for="dict in apartment_room_status"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="房间图片" >
          <image-upload v-model="form.roomImagePath" :limit="5" multiple />
        </el-form-item>
        <el-form-item label="房间属性" prop="roomProperty">
          <el-checkbox-group v-model="form.roomProperty">
            <el-checkbox
                v-for="data in roomproperties"
                :key="data.propertyRoomDataId"
                :label="data.propertyRoomName"
                :value="data.propertyRoomName"
            >{{data.propertyRoomName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看房间详情对话框 -->
    <el-dialog title="房间详情" v-model="detailsOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="房间名称">{{ detailsForm.roomName }}</el-descriptions-item>
        <el-descriptions-item label="所属公寓">{{ detailsForm.flatsName }}</el-descriptions-item>
        <el-descriptions-item label="房间月租">{{ detailsForm.roomMonthRent }}</el-descriptions-item>
        <el-descriptions-item label="房间面积">{{ detailsForm.roomSize }}</el-descriptions-item>
        <el-descriptions-item label="房间状态">
          <dict-tag :options="apartment_room_status" :value="detailsForm.roomStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="房间属性">
          {{ detailsForm.roomProperty ? detailsForm.roomProperty.join(', ') : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="房间图片" :span="2">
          <el-carousel v-if="detailsForm.roomImagePath" :interval="4000" type="card" height="300px">
            <el-carousel-item v-for="(image, index) in detailsForm.roomImagePath.split(',')" :key="index">
              <el-image :src="image" style="width: 100%; height: 100%; object-fit: cover;" />
            </el-carousel-item>
          </el-carousel>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailsOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Room">
import { listRoom, getRoom, delRoom, addRoom, updateRoom ,listRoomAll} from "@/api/apartment/room";
import {ref} from "vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
import ImageUpload from "@/components/ImageUpload/index.vue";
import {findRoomdata} from "@/api/apartment/roomdata.js"
import { flatsLists} from "@/api/apartment/flats";
import NumberCounter from "@/components/NumberCount.vue";


const { proxy } = getCurrentInstance();
const { apartment_room_status } = proxy.useDict('apartment_room_status');

const roomproperties=ref([]);
const roomList = ref([]);
const flatsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const roomLists = ref([]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roomMonthRent: null,
    flatsId: undefined,
    roomStatus: null,
    roomName: null,
    roomProperty: null,
    roomImagePath: null,
    roomUseNo: null,
    roomSize: null
  },
  rules: {
    roomMonthRent: [
      { required: true, message: "房间月租不能为空", trigger: "blur" }
    ],
    roomStatus: [
      { required: true, message: "房间状态不能为空", trigger: "change" }
    ],
    flatsId: [
      { required: true, message: "所属公寓不能为空", trigger: "blur" }
    ],
    roomName: [
      { required: true, message: "房间名称不能为空", trigger: "blur" }
    ],
    roomSize: [
        { required: true, message: "房间面积不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

function getPropertyList() {
  loading.value = true;
  findRoomdata(queryParams.value).then(response => {
    roomproperties.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
import { computed } from 'vue';


const uniqueMonthRents = computed(() => {
  const uniqueRents = new Set(roomLists.value.map(room => room.roomMonthRent));
  return Array.from(uniqueRents).sort((a, b) => a - b);
});
const uniqueRoomSizes = computed(() => {
  const uniqueSizes = new Set(roomLists.value.map(room => room.roomSize));
  return Array.from(uniqueSizes).sort((a, b) => a - b);
});
/** 查询房间管理列表 */
function getList() {
  loading.value = true;
  listRoom(queryParams.value).then(response => {
    roomList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getLists() {
  loading.value = true;
  listRoomAll(queryParams.value).then(response => {
    roomLists.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getFlatsList() {
  loading.value = true;
  flatsLists(queryParams.value).then(response => {
    flatsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    roomId: null,
    flatsId: null,
    roomMonthRent: null,
    roomStatus: null,
    flatsName: null,
    roomName: null,
    roomUseNo: "0"
  };
  proxy.resetForm("roomRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.roomId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
function handleUseNoChange(row) {
  let text = row.roomUseNo === "0" ? "可用" : "停用";
  proxy.$modal.confirm('确认要将"' + row.roomName + '"房间设置为"' + text + '"吗？').then(function() {
    return updateRoom({ roomId: row.roomId, roomUseNo: row.roomUseNo });
  }).then(() => {
    proxy.$modal.msgSuccess("设置成功");
    getList();
  }).catch(function() {
    row.roomUseNo = row.roomUseNo === "0" ? "1" : "0";
  });
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加房间管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _roomId = row.roomId || ids.value
  getRoom(_roomId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改房间管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roomRef"].validate(valid => {
    if (valid) {
      if (form.value.roomId != null) {
        updateRoom(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRoom(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _roomIds = row.roomId || ids.value;
  proxy.$modal.confirm('是否确认删除房间管理编号为"' + _roomIds + '"的数据项？').then(function() {
    return delRoom(_roomIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('apartment/room/export', {
    ...queryParams.value
  }, `room_${new Date().getTime()}.xlsx`)
}

const detailsOpen = ref(false);
const detailsForm = ref({});

/** 查看详情按钮操作 */
function handleViewDetails(row) {
  getRoom(row.roomId).then(response => {
    detailsForm.value = response.data;
    detailsOpen.value = true;
  });
}


getList();
getFlatsList();
getPropertyList();
getLists();
</script>
